import {types,legendColors,typesRenderer,popupTemplate} from '@/views/page/live-weather/config';
import {airQualityLevesByHourOrDay,airQualityValuesByHourOrDay,airQualityColors } from '@/assets/js/config';
import {city, cityPinyin, cityMapCenter, geoserver} from '@/config/env';
const mixins = {
  data(){
    return {
      timeSwitchs: [],
      orginDates: [],
      dates:[],
      dataSource:[],
      renderers: [],
      industries: [],
      timeDefaultValue: new Date(),
      playInterVal: null,
      list:{
        air:[],
        live: []
      },
      
      
    }
  },
  methods:{
    removeLayer(){
      this.layers.forEach(item => {
        if (this.map.getLayer(item)) this.map.removeLayer(item);
        if (this.map.getSource(item)) this.map.removeSource(item);  
      });      
    },
    getListAir(){
      let params = {
        dt_year: 2023,
        dt_month: 6,
        dt_day: 23
      };
      this.$request('get', '/chaqi/daily', params, (data,msg) => {
        this.list.air = data;
        this.addLayerAir()
      })
    },
    getListLive(){
      this.$request('get', '/air/nmc/current', {dt: '2023-06-23'}, (data,msg) => {
        this.list.live = data.filter(i => city.indexOf(i.city) > -1);
        this.addLayerLive();
      })
    },
    async addLayerAir(){
      if (!this.map) {
        return;
      }
      const layerId = 'air-monitor';
      const key = 'aqi';
      const geojson = {
        type: 'FeatureCollection',
        features: [],
      };
      const data = [...this.list.air];
      for await (const d of data) {
        const item = d;
        item[key] = Number(item[key]);
        if (Number(item[key]) > 0) {
          geojson.features.push({
            type: 'Feature',
            geometry: {
              type: 'Point',
              coordinates: [d.lon, d.lat]
            },
            properties: d
          });
        }
      }
      if (!this.map.getSource(layerId)) {
        this.map.addSource(layerId, {
          type: 'geojson',
          data: geojson,
        });
      } else {
        (this.map.getSource(layerId)).setData(geojson);
      }
      const circleColors = [
        'step',
        ['to-number', ['get', key]],
      ];
      const levels = airQualityLevesByHourOrDay.日;
      const values = airQualityValuesByHourOrDay.日;
      values[key].forEach((v, i) => {
        circleColors.push(airQualityColors[levels[key][i]]);
        circleColors.push(v + 0.000001);
      });
      circleColors.push(airQualityColors[levels[key][levels[key].length - 1]]);
      if (!this.map.getLayer(layerId)) {
        this.map.addLayer({
          id: layerId,
          type: 'circle',
          source: layerId,
          paint: {
            'circle-color': circleColors,
            'circle-stroke-width': 1,
            'circle-radius': 6,
            'circle-stroke-color': '#000',
          }
        }, this.map.getLayer('area-border')? 'area-border' : undefined);
          // this.addPopup(layerId);
      } else {
        this.map.setPaintProperty(layerId, 'circle-color', circleColors);
      }
      
      console.log('air',this.map.getStyle().layers)

      // 必须要加上这一句代码，否则setPaintProperty不生效
      this.map.resize();
    },
    addLayerLive(){
        const type = 'temperature';
        if (!legendColors[type].isImage) {
          this.addLayer();
          return;
        }
        const images = legendColors[type].icons;
        images.forEach((img, index) => {
          this.map.loadImage(img.url, (error, image) => {
            if (error) throw error;
            if (!this.map.hasImage(img.id)){
              this.map.addImage(img.id, image);
            }
            if (index === images.length - 1) {
              this.addLayer();
            }
          });
        })
    },
    addLayer(){
      const geojson = {
        type: 'FeatureCollection',
        features: [],
      };
      const type = 'temperature';
      for(const d of this.list.live) {
        const item = d;
        if (Number(item[type]) !== null) {
          geojson.features.push({
            type: 'Feature',
            geometry: {
              type: 'Point',
              coordinates: [d.lon, d.lat]
            },
            properties: d
          });
        }
      }
      if (this.map.getLayer('live-weather-label')) {
        this.map.removeLayer('live-weather-label');
      }
      if (this.map.getLayer('live-weather-layer')) {
        this.map.removeLayer('live-weather-layer');
      }
      this.map.resize();
      if (!this.map.getSource('live-weather-source')) {
        this.map.addSource('live-weather-source', {
          type: 'geojson',
          data: geojson
        });
      } else {
        (this.map.getSource('live-weather-source')).setData(geojson);
      }
      let newTypeR = JSON.parse(JSON.stringify(typesRenderer));
      if (!this.map.getLayer('live-weather-layer')) {
        newTypeR[type].layer.id = 'live-weather-layer';
        newTypeR[type].layer.source = 'live-weather-source',
        this.map.addLayer(newTypeR[type].layer, this.map.getLayer('area-border')? 'area-border' : undefined);
      }
      if (type !== 'wind_speed'  && !this.map.getLayer('live-weather-label') ){
        newTypeR.label.layer.layout['text-field'][1] = type;
        newTypeR.label.layer.id = 'live-weather-label';
        newTypeR.label.layer.source = 'live-weather-source';
        newTypeR.label.layer.layout['text-font'] = ['Noto Sans Regular']
        this.map.addLayer(newTypeR.label.layer, this.map.getLayer('area-border')? 'area-border' : undefined);
      }
      this.map.resize();
    },

    
  }
}
export default mixins;